extends "res://scene/character/character_base.gd"

@export var target_name_hint: String = "Castle1"

@export var on_ship: bool = true # 乘船状态：为真时保持静止，靠岸后改为false

@onready var anim: AnimatedSprite2D = get_node_or_null("AnimatedSprite2D")
@onready var attack_area: Area2D = get_node_or_null("AttackArea")
@onready var body_shape: CollisionShape2D = $CollisionShape2D2
@onready var sfx_player: AudioStreamPlayer2D = get_node_or_null("SfxPlayer")
@export var attack_sfx: AudioStream
@onready var _agent: NavigationAgent2D = get_node_or_null("NavigationAgent2D")
var _attacking: bool = false
var _disembarking: bool = false
var _dock_point: Vector2 = Vector2.ZERO
@export var dock_arrive_threshold: float = 6.0


func _ready() -> void:
	# 基类属性配置
	max_health = 25
	attack_interval = 1.2
	self_group = "enemy"
	target_group = "building"
	tracking_radius = 800.0
	super._ready()

	# 连接 AttackArea 信号（如果存在）
	if attack_area:
		attack_area.area_entered.connect(_on_attack_area_entered)
		attack_area.area_exited.connect(_on_attack_area_exited)

	# 若在船上，暂不寻找目标；靠岸后再开始
	if on_ship:
		if body_shape:
			body_shape.disabled = true
		if attack_area:
			attack_area.monitoring = false
		var hurt_area: Area2D = get_node_or_null("HurtArea")
		if hurt_area:
			hurt_area.monitoring = false
		if anim:
			anim.play("idle")

	# 连接动画帧变化，用于按“每次挥砍”播放音效
	if anim:
		anim.frame_changed.connect(_on_anim_frame_changed)


func _physics_process(delta: float) -> void:
	# 在船上：直接待机并返回
	if on_ship:
		velocity = Vector2.ZERO
		if anim:
			anim.play("idle")
		move_and_slide()
		return

	# 攻击中：停下不移动，仅播放攻击动画
	attack_timer = max(0.0, attack_timer - delta)
	if _attacking:
		velocity = Vector2.ZERO
		if anim:
			anim.play("attack_right")
		move_and_slide()
		return

	# 下船阶段：缓行到最近导航点
	if _disembarking and _agent:
		if _agent.is_navigation_finished():
			if global_position.distance_to(_dock_point) <= dock_arrive_threshold:
				_disembarking = false
				velocity = Vector2.ZERO
				move_and_slide()
				return
		var next_point_dock: Vector2 = _agent.get_next_path_position()
		velocity = (next_point_dock - global_position).normalized() * move_speed
		if anim:
			anim.play("run_right")
		move_and_slide()
		return

	# 常规：使用基类的寻路与移动
	super._physics_process(delta)
	if anim:
		if velocity.length() > 0.0:
			anim.play("run_right")
		else:
			anim.play("idle")




# --- 攻击逻辑 ---
func _on_attack_area_entered(area: Area2D) -> void:
	if target and _area_belongs_to_target(area):
		_start_attack()

func _on_attack_area_exited(area: Area2D) -> void:
	if _attacking and target and _area_belongs_to_target(area):
		_stop_attack()

func _start_attack() -> void:
	_attacking = true
	velocity = Vector2.ZERO
	if anim:
		anim.play("attack_right")

func _stop_attack() -> void:
	_attacking = false
	# 可选：恢复寻路由基类处理

func _on_anim_frame_changed() -> void:
	if anim == null:
		return
	# 在攻击动画的每次循环开始（frame==0）播放音效
	if _attacking and anim.animation == "attack_right":
		if anim.frame == 0:
			if sfx_player:
				if attack_sfx:
					sfx_player.stream = attack_sfx
				if sfx_player.stream:
					sfx_player.play()

func _area_belongs_to_target(n: Node) -> bool:
	var p: Node = n
	while p:
		if p == target:
			return true
		p = p.get_parent()
	return false



func goAshore() -> void:
	# 船只靠岸后由外部调用，切换为步行逻辑并开始寻路
	if on_ship:
		on_ship = false
		# 恢复碰撞与区域监控
		if body_shape:
			body_shape.disabled = false
		if attack_area:
			attack_area.monitoring = true
		var hurt_area: Area2D = get_node_or_null("HurtArea")
		if hurt_area:
			hurt_area.monitoring = true

		# 设定最近导航点为临时目标，下船缓行过去
		if _agent:
			var map_rid: RID = _agent.get_navigation_map()
			if map_rid.is_valid():
				_dock_point = NavigationServer2D.map_get_closest_point(map_rid, global_position)
				if _dock_point == Vector2.ZERO:
					_dock_point = global_position
				_disembarking = true
				_agent.target_position = _dock_point
				if anim:
					anim.play("run_right")

func get_damage(amount: float, source: Node = null) -> void:
	super.get_damage(amount, source)
	print("受到" + str(amount) + "点伤害")
	if current_health > 0.0:
		_switch_target_to_nearest_soldier(source)

func _switch_target_to_nearest_soldier(attacker: Node = null) -> void:
	# 切换追踪分组为士兵，并优先锁定攻击者
	target_group = "army"
	if attacker and attacker is Node2D and not attacker.is_in_group("enemy"):
		target = attacker
		print("切换攻击目标成士兵")
	else:
		_update_target()
